﻿using System;
using System.Collections.Generic;
using System.Windows.Media;


    // ReSharper disable CheckNamespace
    namespace System.Windows
    // ReSharper restore CheckNamespace
    {
        public static class DependencyObjectExtensions
        {
            public static IEnumerable<DependencyObject> VisualChildren(this DependencyObject me)
            {
                int childrenCount = VisualTreeHelper.GetChildrenCount(me);

                for (int i = 0; i < childrenCount; i++)
                {
                    yield return VisualTreeHelper.GetChild(me, i);
                }

            }

            public static bool HasChild(this DependencyObject parent, DependencyObject child)
            {
                DependencyObject current = child;
                do
                {
                    current = VisualTreeHelper.GetParent(current);
                }
                while (current != null && current != parent);
                return current != null;

            }

            public static T FindVisualParent<T>(this DependencyObject initial) where T : class
            {
                DependencyObject current = initial;

                while (current != null)
                {
                    current = VisualTreeHelper.GetParent(current);
                    if (current is T)
                        return current as T;
                }

                return default(T);
            }
        }
    }

